<template>
  <div class="auth-container">
    <div class="info-container">
      <div class="info-label">Authorization:</div>
      <div class="info-value">{{ maskedAuth }}</div>
    </div>
    <div class="info-container">
      <div class="info-label">公司ID:</div>
      <div class="info-value">{{ ptoken }}</div>
    </div>
    
    <div class="auth-actions">
      <button @click="getAuthFromERP" class="auth-button" :disabled="isAuthLoading">
        {{ isAuthLoading ? '正在获取...' : '获取认证信息' }}
      </button>
    </div>
    
    <div class="info-container">
      <div class="info-label">Whatsapp账号或者手机号(包含国家编码86xxxx):</div>
      <input type="text" v-model="whatsappAccount" class="info-input">
      <button @click="saveAccount" class="save-button">保存</button>
    </div>
    
    <div class="info-container">
      <div class="info-label">自动翻译对话:</div>
      <div class="toggle-container">
        <label class="toggle-switch">
          <input type="checkbox" v-model="autoTranslate" @change="saveAutoTranslate">
          <span class="toggle-slider"></span>
        </label>
        <span class="toggle-label">{{ autoTranslate ? '已开启' : '已关闭' }}</span>
      </div>
    </div>
    
    <div :class="['status', statusType]" v-if="statusMessage">{{ statusMessage }}</div>

    <dialog ref="accountDialog">
      <p>请输入 WhatsApp Account ID</p>
      <input type="text" v-model="dialogAccount" placeholder="86">
      <div class="dialog-buttons">
        <button @click="confirmAccount">确认</button>
        <button @click="cancelAccount">取消</button>
      </div>
    </dialog>

    <dialog ref="mismatchDialog">
      <p>检测到填写的WhatsApp账号与当前使用的不匹配！</p>
      <p>当前填写: <strong>{{ whatsappAccount }}</strong></p>
      <p>实际使用: <strong>{{ currentWhatsAppId }}</strong></p>
      <div class="dialog-buttons">
        <button @click="useCurrentWhatsAppId">使用实际账号</button>
        <button @click="keepUserAccount">保持现有账号</button>
      </div>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { URL_CONFIG } from '../utils/defines'

// Storage keys
const STORAGE_KEYS = {
  AUTH: 'kiki_auth',
  PTOKEN: 'kiki_ptoken',
  ACCOUNT_ID: 'whatsapp_account_id',
  AUTO_TRANSLATE: 'kiki_auto_translate'
}

const auth = ref('')
const ptoken = ref('')
const whatsappAccount = ref('')
const autoTranslate = ref(false)
const statusMessage = ref('')
const statusType = ref('success')
const dialogAccount = ref('86')
const accountDialog = ref<HTMLDialogElement>()
const mismatchDialog = ref<HTMLDialogElement>()
const isAuthLoading = ref(false)
const currentWhatsAppId = ref('')

// 计算属性：遮罩后的 Authorization
const maskedAuth = computed(() => {
  if (!auth.value) return ''
  if (auth.value.length <= 5) return auth.value
  const lastFive = auth.value.slice(-5)
  const maskedPart = '*'.repeat(10)
  return `${maskedPart}${lastFive}`
})

// 更新状态显示
const updateStatus = (message: string, isSuccess = true) => {
  statusMessage.value = message
  statusType.value = isSuccess ? 'success' : 'warning'
  setTimeout(() => {
    statusMessage.value = ''
  }, 3000)
}

// 获取ERP认证信息
const getAuthFromERP = async () => {
  isAuthLoading.value = true
  updateStatus('正在打开ERP网站获取认证信息...')
  
  try {
    // 打开ERP网站
            chrome.tabs.create({ url: URL_CONFIG.ERP_BASE_URL + '/' }, (tab) => {
      // 设置一个定时器，每隔2秒检查一次认证信息
      const checkAuthInterval = setInterval(async () => {
        const result = await chrome.storage.local.get([STORAGE_KEYS.AUTH, STORAGE_KEYS.PTOKEN])
        
        // 如果获取到了认证信息，更新UI并关闭定时器
        if (result[STORAGE_KEYS.AUTH] && result[STORAGE_KEYS.PTOKEN]) {
          clearInterval(checkAuthInterval)
          auth.value = result[STORAGE_KEYS.AUTH]
          ptoken.value = result[STORAGE_KEYS.PTOKEN]
          isAuthLoading.value = false
          updateStatus('认证信息已成功获取')
        }
      }, 2000)
      
      // 30秒后如果还没有获取到认证信息，停止检查
      setTimeout(() => {
        clearInterval(checkAuthInterval)
        if (!auth.value || !ptoken.value) {
          isAuthLoading.value = false
          updateStatus('获取认证信息超时，请确保已登录ERP系统', false)
        }
      }, 30000)
    })
  } catch (error) {
    isAuthLoading.value = false
    updateStatus('打开ERP网站失败，请重试', false)
  }
}

// 保存账号
const saveAccount = async () => {
  try {
    await chrome.storage.local.set({ [STORAGE_KEYS.ACCOUNT_ID]: whatsappAccount.value })
    updateStatus('WhatsApp账号已保存')
  } catch (error) {
    updateStatus('保存失败，请重试', false)
  }
}

// 保存自动翻译设置
const saveAutoTranslate = async () => {
  try {
    await chrome.storage.local.set({ [STORAGE_KEYS.AUTO_TRANSLATE]: autoTranslate.value })
    updateStatus(`自动翻译已${autoTranslate.value ? '开启' : '关闭'}`)
    
    // 发送消息通知内容脚本更新自动翻译设置
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]?.id) {
        chrome.tabs.sendMessage(tabs[0].id, { 
          action: 'updateAutoTranslate', 
          value: autoTranslate.value 
        })
      }
    })
  } catch (error) {
    updateStatus('保存设置失败，请重试', false)
  }
}

// 确认对话框账号
const confirmAccount = async () => {
  whatsappAccount.value = dialogAccount.value
  try {
    await chrome.storage.local.set({ [STORAGE_KEYS.ACCOUNT_ID]: dialogAccount.value })
    accountDialog.value?.close()
    updateStatus('账号已保存')
  } catch (error) {
    updateStatus('保存失败，请重试', false)
  }
}

// 取消对话框
const cancelAccount = () => {
  accountDialog.value?.close()
  updateStatus('请填写 WhatsApp 账号', false)
}

// 加载认证信息
const loadAuthInfo = async () => {
  try {
    const result = await chrome.storage.local.get([
      STORAGE_KEYS.AUTH,
      STORAGE_KEYS.PTOKEN,
      STORAGE_KEYS.ACCOUNT_ID,
      STORAGE_KEYS.AUTO_TRANSLATE
    ])
    
    auth.value = result[STORAGE_KEYS.AUTH] || ''
    ptoken.value = result[STORAGE_KEYS.PTOKEN] || 'Not found'
    whatsappAccount.value = result[STORAGE_KEYS.ACCOUNT_ID] || ''
    autoTranslate.value = result[STORAGE_KEYS.AUTO_TRANSLATE] || false

    if (!result[STORAGE_KEYS.ACCOUNT_ID]) {
      accountDialog.value?.showModal()
    }

    if (auth.value && ptoken.value) {
      updateStatus('认证信息已获取')
    } else {
      updateStatus('请先访问 ERP 页面获取认证信息', false)
    }
  } catch (error) {
    updateStatus('加载认证信息失败', false)
  }
}

// 获取当前WhatsApp用户ID
const getCurrentWhatsAppUserId = async (): Promise<string> => {
  return new Promise((resolve) => {
    // 向当前活动标签页发送获取用户ID的消息
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]?.id) {
        chrome.tabs.sendMessage(tabs[0].id, { action: 'getCurrentWhatsAppUserId' }, (response) => {
          if (response && response.userId) {
            resolve(response.userId)
          } else {
            resolve('')
          }
        })
      } else {
        resolve('')
      }
    })
  })
}

// 使用当前WhatsApp ID
const useCurrentWhatsAppId = async () => {
  whatsappAccount.value = currentWhatsAppId.value
  try {
    await chrome.storage.local.set({ [STORAGE_KEYS.ACCOUNT_ID]: currentWhatsAppId.value })
    mismatchDialog.value?.close()
    updateStatus('已更新为当前使用的WhatsApp账号')
  } catch (error) {
    updateStatus('保存失败，请重试', false)
  }
}

// 保持用户设置的账号
const keepUserAccount = () => {
  mismatchDialog.value?.close()
  updateStatus('保持现有账号设置')
}

// 监听认证信息变化
onMounted(async () => {
  await loadAuthInfo()
  
  // 获取当前WhatsApp ID并进行比较
  const currentId = await getCurrentWhatsAppUserId()
  currentWhatsAppId.value = currentId
  
  if (currentId) {
    if (!whatsappAccount.value) {
      // 如果用户没有填写账号，自动填充当前ID
      whatsappAccount.value = currentId
      await chrome.storage.local.set({ [STORAGE_KEYS.ACCOUNT_ID]: currentId })
      updateStatus('已自动填充当前使用的WhatsApp账号')
    } else if (whatsappAccount.value !== currentId) {
      // 如果账号不匹配，显示确认对话框
      mismatchDialog.value?.showModal()
    }
  }
  
  // 监听存储变化
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'local') {
      if (changes[STORAGE_KEYS.AUTH] || changes[STORAGE_KEYS.PTOKEN]) {
        auth.value = changes[STORAGE_KEYS.AUTH]?.newValue || auth.value
        ptoken.value = changes[STORAGE_KEYS.PTOKEN]?.newValue || ptoken.value
        
        if (auth.value && ptoken.value) {
          updateStatus('认证信息已更新')
        }
      }
    }
  })
})
</script>

<style scoped>
.auth-container {
  padding: 16px;
  background-color: #f0f2f5;
  border-radius: 8px;
  margin-bottom: 16px;
}

.info-container {
  margin-bottom: 16px;
}

.info-label {
  font-weight: bold;
  margin-bottom: 4px;
  color: #111b21;
}

.info-value {
  padding: 8px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #ddd;
  color: #54656f;
}

.auth-actions {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
}

.auth-button {
  background: #00a884;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 200px;
}

.auth-button:hover {
  background: #008f6f;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.auth-button:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.info-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 8px;
}

.save-button {
  background-color: #00a884;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.save-button:hover {
  background-color: #008f6f;
}

.toggle-container {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.toggle-switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
  margin-right: 10px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 20px;
}

.toggle-slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .toggle-slider {
  background-color: #00a884;
}

input:checked + .toggle-slider:before {
  transform: translateX(20px);
}

.toggle-label {
  font-size: 14px;
  color: #54656f;
}

.status {
  padding: 8px;
  border-radius: 4px;
  margin-top: 16px;
  text-align: center;
  font-weight: bold;
}

.success {
  background-color: #d4edda;
  color: #155724;
}

.warning {
  background-color: #f8d7da;
  color: #721c24;
}

dialog {
  border: none;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 80%;
  max-width: 400px;
}

dialog p {
  margin-top: 0;
  font-weight: bold;
}

dialog input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 16px;
}

dialog strong {
  color: #00a884;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.dialog-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-buttons button:first-child {
  background-color: #00a884;
  color: white;
}

.dialog-buttons button:last-child {
  background-color: #f0f2f5;
  color: #54656f;
}
</style>
